package cn.melon.mod.library;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.melon.common.ModelType;
import cn.melon.helper.BaseRequset;
import cn.melon.helper.IOnRequestListener;
import cn.melon.helper.LoggerHelper;
import cn.melon.helper.RequestHelper;
import cn.melon.view.admin.library.IUpdateBookTable;
import cn.melon.window.MainWindow;

public class LibraryRequest extends BaseRequset{
    
    private String TAG = LoggerHelper.makeLogTag(LibraryRequest.class);
    private Logger libLogger = LoggerHelper.clientLogger();
    
    private IUpdateBookTable updateGoodsTable;
    private MainWindow m = null;
    
    public LibraryRequest() {
    }
    
    public LibraryRequest(MainWindow m) {
        this.m = m;
    }
    
    public LibraryRequest(IUpdateBookTable updateBookTable) {
        this.updateGoodsTable = updateBookTable;
    }

    @Override
    public void makeRequset() {
        //getBorrowBooks();
        //getHotBooks();
        //getAllBooks();
        
        LibraryBooksInfo booksInfo = new LibraryBooksInfo();
        booksInfo.setBookName("Orange'S:一个操作系统的实现");
        booksInfo.setBookID("2310780");
        booksInfo.setPublisher("北京:电子工业出版社,2009");
        booksInfo.setLoanable("0");
        booksInfo.setAuthor("于渊著");
        booksInfo.setBorrowStudent("09014312");
        booksInfo.setBorrowDate("2016-05-31");
        booksInfo.setDDL("2016-10-10");
        booksInfo.setReturnDate("");
        
        //addInfo(booksInfo);
        //updateInfo(booksInfo);
//        getAllBooks();
        
    }
    
    /**
     * 续借图书
     * @param bookID 图书编号 
     */
    public void reNew(String bookID) {
        JSONObject jReq = new JSONObject();
        try {
            jReq.put("action", "RENEWBOOK");
            jReq.put("content", bookID);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new RequestHelper(ModelType.LIBRARY)
        .addRequest(jReq.toString())
        .addReceiver("librenew", new IOnRequestListener() {
            
            @Override
            public void onSuccess(String response) {
                libLogger.debug(TAG + response);
                try {
                    JSONObject jRes = new JSONObject(response);
                    if(jRes.getInt("code") == 200) {
                        String jContent = jRes.getString("content");
                        libLogger.debug(TAG + jContent);
                        getBorrowBooks();
                    } else {
                        JOptionPane.showMessageDialog(null, "续借图书失败", "", JOptionPane.ERROR_MESSAGE);
                        System.out.println("续借图书失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).build().start();
        
    }
    
    /**
     * 添加书籍信息
     * @param info 书籍信息
     */
    public void addInfo(LibraryBooksInfo info) {
        JSONObject jReq = new JSONObject();
        try {
            jReq.put("action", "ADDBOOK");
            jReq.put("content", info.toJSON());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new RequestHelper(ModelType.LIBRARY)
        .addRequest(jReq.toString())
        .addReceiver("libaddinfo", new IOnRequestListener() {
            
            @Override
            public void onSuccess(String response) {
                libLogger.debug(TAG + response);
                try {
                    JSONObject jRes = new JSONObject(response);
                    if(jRes.getInt("code") == 200) {
                        String jContent = jRes.getString("content");
                        libLogger.debug(TAG + jContent);
                    } else {
                        System.out.println("获取所有图书失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).build().start();
    }
    
    /**
     * 更新图书信息
     * @param info 图书信息
     */
    public void updateInfo(LibraryBooksInfo info) {
        
        JSONObject jReq = new JSONObject();
        try {
            jReq.put("action", "UPDATEBOOK");
            jReq.put("content", info.toJSON());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new RequestHelper(ModelType.LIBRARY)
        .addRequest(jReq.toString())
        .addReceiver("libupdate", new IOnRequestListener() {
            
            @Override
            public void onSuccess(String response) {
                libLogger.debug(TAG + response);
                try {
                    JSONObject jRes = new JSONObject(response);
                    if(jRes.getInt("code") == 200) {
                        String jContent = jRes.getString("content");
                        libLogger.debug(TAG + jContent);
                        getAllBooks();
                    } else {
                        System.out.println("获取所有图书失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).build().start();
    }
    
    /**
     * 获取当期借阅图书的信息
     */
    public void getBorrowBooks() {
        JSONObject jReq = new JSONObject();
        try {
            jReq.put("action", "ASKBORROW");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new RequestHelper(ModelType.LIBRARY)
        .addRequest(jReq.toString())
        .addReceiver("libborrow", new IOnRequestListener() {
            
            @Override
            public void onSuccess(String response) {
                libLogger.debug(TAG + response);
                List<LibraryBooksInfo> infoList = new ArrayList<>();
                try {
                    JSONObject jRes = new JSONObject(response);
                    if(jRes.getInt("code") == 200) {
                        JSONArray jContent = jRes.getJSONArray("content");
                        m.removeAllBooks();
                        for (int i = 0; i < jContent.length(); i++) {

                            LibraryBooksInfo info = 
                                    LibraryBooksInfo.toInfo((JSONObject) jContent.get(i));
                            infoList.add(info);
                            if (m != null) {
                                m.addLentBook(info);
                            }
                        }
                    } else {
                        System.out.println("获取借阅图书失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).build().start();
    }
    
    /**
     * 获取当前热门图书
     */
    public void getHotBooks() {
        JSONObject jReq = new JSONObject();
        try {
            jReq.put("action", "ASKHOT");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new RequestHelper(ModelType.LIBRARY)
        .addRequest(jReq.toString())
        .addReceiver("libhot", new IOnRequestListener() {
            
            @Override
            public void onSuccess(String response) {
                libLogger.debug(TAG + response);
                List<LibraryBooksInfo> infoList = new ArrayList<>();
                try {
                    JSONObject jRes = new JSONObject(response);
                    if(jRes.getInt("code") == 200) {
                        JSONArray jContent = jRes.getJSONArray("content");
                        for (int i = 0; i < jContent.length(); i++) {

                            LibraryBooksInfo info = 
                                    LibraryBooksInfo.toInfo((JSONObject) jContent.get(i));
                            infoList.add(info);
                        }
                        if (updateGoodsTable != null) {
                            updateGoodsTable.updateTable(infoList);
                        }
                    } else {
                        System.out.println("获取热门图书失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).build().start();
    }
    
    /**
     * 获取所有图书
     */
    public void getAllBooks() {
        JSONObject jReq = new JSONObject();
        try {
            jReq.put("action", "ALLBOOKS");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new RequestHelper(ModelType.LIBRARY)
        .addRequest(jReq.toString())
        .addReceiver("liball", new IOnRequestListener() {
            
            @Override
            public void onSuccess(String response) {
                libLogger.debug(TAG + response);
                List<LibraryBooksInfo> infoList = new ArrayList<>();
                try {
                    JSONObject jRes = new JSONObject(response);
                    if(jRes.getInt("code") == 200) {
                        JSONArray jContent = jRes.getJSONArray("content");
                        for (int i = 0; i < jContent.length(); i++) {

                            LibraryBooksInfo info = 
                                    LibraryBooksInfo.toInfo((JSONObject) jContent.get(i));
                            infoList.add(info);
                        }
                        if (updateGoodsTable != null) {
                            updateGoodsTable.updateTable(infoList);
                        }
                    } else {
                        System.out.println("获取所有图书失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).build().start();
    }
}
